const redisClient = require('../config/redis');

const redisCache = async (req, res, next) => {
  const { method, url } = req;
  const cacheKey = `${method}${url}`;
  if (method === 'GET') {
    try {
      // 尝试从 Redis 获取缓存
      const cachedData = await redisClient.get(cacheKey);
      if (cachedData) {
        // 如果有缓存，直接返回缓存数据
        return res.json(JSON.parse(cachedData));
      }
      // 如果没有缓存，继续请求数据库
      req.cacheKey = cacheKey;
      next();
    } catch (error) {
      console.error('Redis 缓存中间件出错:', error);
      next(); // 即使 Redis 出错，也继续执行后续逻辑
    }
  } else {
    // 非 GET 请求无需缓存，直接继续
    next();
  }
};

module.exports = redisCache;